import { Box, Typography } from '@mui/material';
import { useRouter } from 'next/router';
import * as React from 'react';
import { useEffect, useRef, useState } from 'react';

import { AuthenticationType } from '../../api/authentication/authentication';
import AuthenticationManager from '../../api/authentication/authentication-manager';
import OrganizationManager from '../../api/organization/organization-manager';
import { BRANDING } from '../../constants/branding';
import Routes, { ALLOW_RETURN_URL } from '../../constants/routes';
import { RETURN_URL } from '../../constants/storage-key';
import Router from '../../libs/router';
import Web3Manager from '../../libs/web3-manager';
import { Organization } from '../../api/organization/organization';

export const WaitLayout = () => {
    return (
        <>
            <style jsx global>{`
                .container-galaxy {
                    height: calc(100vh);
                    background-image: url(/galaxy-bg.svg);
                    background-size: cover;
                }

                .galaxy {
                    height: 100%;
                    background-image: url(/item.svg);
                    background-repeat: no-repeat;
                    background-position: center;
                    background-size: contain;
                }

                .content {
                    height: 100%;
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;
                }
            `}</style>
            <Box className={'container-galaxy'}>
                <Box className={'content'}>
                    <Typography variant="h2">Connecting your {BRANDING.NAME} account...</Typography>
                </Box>
            </Box>
        </>
    );
};

export const UserContext = React.createContext({
    organization: null,
    authenticationType: AuthenticationType.NOT_WHITELISTED,
    walletAddress: undefined
});

function ControlNavigation({ children }) {
    const router = useRouter();
    const previousUrl = useRef(null);

    const [doneYY, setDoneYY] = useState(false);
    const [organization, setOrganization] = useState<Organization>(null);
    const [authenticationType, setAuthenticationType] = useState<AuthenticationType>(null);
    const [walletAddress, setWalletAddress] = useState<string>(undefined);

    useEffect(() => {
        const handleRouteChange = async (url) => {
            if (
                url === Routes.HOME &&
                (previousUrl.current === Routes.OTP ||
                    previousUrl.current === Routes.CONNECT_WALLET)
            ) {
                setDoneYY(false);
                const organization = await OrganizationManager.getProfile();

                if (!organization) {
                    await router.push(Routes.UNAUTHORIZED);
                } else {
                    setOrganization(organization);
                }
                setDoneYY(true);
            }
            previousUrl.current = url;
        };

        router.events.on('routeChangeComplete', handleRouteChange);
        return () => {
            router.events.off('routeChangeComplete', handleRouteChange);
        };
    }, [router.events]);

    useEffect(() => {
        const checkWeb3Wallet = async () => {
            const isWalletConnected = await Web3Manager.isWalletConnected();

            if (isWalletConnected == true) {
                await handleAccountsChanged();
            } else {
                await router.push(Routes.CONNECT_WALLET);
            }
            setDoneYY(true);
        };

        checkWeb3Wallet().then();
    }, []);

    const handleAuthenticationStatus = async (valid: AuthenticationType) => {
        if (valid === AuthenticationType.VALID) {
            const aa:Organization = await OrganizationManager.getProfile();

            if (!aa) {
                await router.push(Routes.UNAUTHORIZED);
            } else {
                setOrganization(aa);
            }
        } else if (valid === AuthenticationType.NOT_AUTHORIZED) {
            if (Router.getCurrent() !== Routes.WRONG_WALLET) {
                if (ALLOW_RETURN_URL.find((url) => Router.getCurrent().startsWith(url))) {
                    localStorage.setItem(RETURN_URL, location.pathname);
                }
                await router.push(Routes.OTP);
            }
        } else {
            await router.push(Routes.WRONG_WALLET);
        }
    };

    const handleAccountsChanged = async () => {
        const walletAddress = await Web3Manager.getWalletAddress();
        setWalletAddress(walletAddress);
        if (walletAddress) {
            const valid = await AuthenticationManager.isValid();
            setAuthenticationType(valid);
            await handleAuthenticationStatus(valid);
        } else {
            // assume that we can't get wallet address here mean we need to connect wallet
            await router.push(Routes.CONNECT_WALLET);
        }
    };

    useEffect(() => {
        (window['ethereum'] as any).on('accountsChanged', handleAccountsChanged);
        return () => {
            (window['ethereum'] as any).removeListener('accountsChanged', handleAccountsChanged);
        };
    }, []);

    // console.log('organization==',organization, authenticationType, walletAddress);

    // return (
    //     <UserContext.Provider value={{ organization, authenticationType, walletAddress }}>
    //         {children}
    //     </UserContext.Provider>
    // );

    return (doneYY) ? (
        <UserContext.Provider value={{ organization, authenticationType, walletAddress }}>
            {children}
        </UserContext.Provider>
    ) : (
        <WaitLayout />
    );
}

export default ControlNavigation;
